package com.sh.threadsync;

/**
 * @Auther: sh
 * @Version 1.0
 * @Description:
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();


        Thread thread = new Thread(buyTicket, "A");
        Thread thread1 = new Thread(buyTicket, "B");
        new Thread(buyTicket, "C").start();
        thread.start();
        thread1.start();


    }
}


class BuyTicket implements Runnable {
    private int ticketNum = 10;
    boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            try {
                Thread.sleep(10);
                buy();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private synchronized void buy() throws InterruptedException {

            if (ticketNum <= 0) {

                flag = false;
                return;
            }
            Thread.sleep(100); // 模拟延迟
            System.out.println(Thread.currentThread().getName() + " 买到了第 " + ticketNum-- + " 张票");
    }
}

